use crate::error::AppError;
use crate::models::chat;
use crate::models::chat::Chat;
use crate::vo::validate_is_not_empty;
use chrono::{DateTime, Local};
use jwt_simple::prelude::{Deserialize, Serialize};
use validator::Validate;

#[derive(Debug, Serialize, Deserialize, Validate)]
pub struct ChatReq {
    #[validate(custom(function = "validate_is_not_empty"))]
    pub name: String,

    pub user_id: i32,

    #[validate(custom(function = "validate_is_not_empty"))]
    pub member_id: String,

    #[validate(range(min = 1, max = 10))]
    pub chat_type: i8,

    pub message_id: i32,

    pub content: String,
}

impl TryFrom<ChatReq> for chat::Chat {
    type Error = AppError;

    fn try_from(value: ChatReq) -> Result<Self, Self::Error> {
        Ok(Chat {
            id: Default::default(),
            name: value.name,
            user_id: value.user_id,
            members_id: value.member_id,
            message_id: value.message_id,
            chat_type: value.chat_type,
            content: value.content,
            create_at: Local::now(),
            update_at: Local::now(),
        })
    }
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Validate)]
pub struct PaginationParams {
    pub page: Option<u32>,
    pub size: Option<u32>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct ChatRes {
    pub id: i32,
    pub name: String,
    pub user_id: i32,
    pub member_id: String,
    pub message_id: i32,
    pub chat_type: i8,
    pub content: String,
    #[serde(
        serialize_with = "crate::common::serialize",
        deserialize_with = "crate::common::deserialize"
    )]
    pub create_at: DateTime<Local>,
    #[serde(
        serialize_with = "crate::common::serialize",
        deserialize_with = "crate::common::deserialize"
    )]
    pub update_at: DateTime<Local>,
}

impl From<Chat> for ChatRes {
    fn from(chat: Chat) -> Self {
        ChatRes {
            id: chat.id,
            name: chat.name,
            user_id: chat.user_id,
            member_id: chat.members_id,
            message_id: chat.message_id,
            chat_type: chat.chat_type,
            content: chat.content,
            create_at: chat.create_at,
            update_at: chat.update_at,
        }
    }
}
